<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Writing Own Ruby Methods: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby methods,ruby study notes,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/writing_own_ruby_methods.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->

</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">
            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Writing Own Ruby Methods</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/more_on_ruby_methods.html">&lt;More on Ruby Methods | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_ri_tool.html">Ruby ri Tool&gt;</a>
                  </strong>
                </p>

                <p>Let's look at writing one's own methods in Ruby with the help of a simple program <strong>p008mymethods.rb</strong>. Observe that we use <strong>def</strong> and <strong>end</strong> to declare a method. Parameters are simply a list of local variable names in parentheses.</p>

                <p class="post-note">We do not declare the return type; a method returns the value of the last statement executed in the method. It is recommended that you leave a single blank line between each method definition. The parentheses around a method's arguments are optional; our convention is to use them when a method has arguments and omit them when it doesn't. In Rails, you will see methods calls with no parentheses.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p008mymethods.rb
                # A method returns the value of the last line
                # Methods that act as queries are often named with a trailing ?
                # Methods that are "dangerous," or modify the receiver, might be named
                # with a trailing ! (Bang methods)
                # A simple method
                def hello
                  'Hello'
                end
                #use the method
                puts hello

                # Method with an argument - 1
                def hello1(name)
                  'Hello ' + name
                end
                puts(hello1('satish'))

                # Method with an argument - 2
                def hello2 name2
                  'Hello ' + name2
                end
                puts(hello2 'talim')
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output when I ran the program on my PC was:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p008mymethods.rb
                Hello
                Hello satish
                Hello talim
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Ruby lets you specify default values for a method's arguments-values that will be used if the caller doesn't pass them explicitly. You do this using the assignment operator. See example <strong>p009mymethods1.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p009mymethods1.rb
                # interpolation refers to the process of inserting the result of an
                # expression into a string literal
                # the interpolation operator #{...} gets calculated separately
                def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank")
                  "#{arg1}, #{arg2}, #{arg3}."
                end
                puts mtd
                puts mtd("ruby")
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output when I ran the program on my PC was:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p009mymethods1.rb
                Dibya, Shashank, Shashank.
                ruby, Shashank, Shashank.
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Please note that as of now, there is no way, to specify a value for the second parameter and use the default value of the first parameter.</p>

                <p>In the above program the interpolation operator #{...} gets calculated separately and the results of the calculation are pasted automatically into the string. When you run these lines, you don't see the #{...} operator on your screen; instead, you see the <em>results</em> of calculating or <em>evaluating</em> what was inside that operator.</p>

                <p><strong>Note</strong>: Interpolation refers to the process of inserting the result of an expression into a string literal. The way to interpolate within a string is to place the expression within #{ and } symbols. An example demonstrates this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts "100 * 5 = #{100 * 5}"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>This displays:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                100 * 5 = 500
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The #{100 * 5} section interpolates the result of 100 * 5 into the string at that position, resulting in the output (500) as shown.</p>

                <p>The example <strong>p010aliasmtd.rb</strong> talks about Aliasing a method.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                alias new_name old_name
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>creates a new name that refers to an existing method. When a method is aliased, the new name refers to a copy of the original method's body. If the method is subsequently redefined, the aliased name will still invoke the original implementation.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p010aliasmtd.rb
                # alias new_name old_name
                # When a method is aliased, the new name refers
                # to a copy of the original method's body

                def oldmtd
                  "old method"
                end
                alias newmtd oldmtd
                def oldmtd
                  "old improved method"
                end
                puts oldmtd
                puts newmtd
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p010aliasmtd.rb
                old improved method
                old method
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note"><strong>alias</strong> creates a new name that refers to an existing method, operator, global variable, or regular expression backreference ($&amp;, $`, $', and $+). Local variables, instance variables, class variables, and constants may not be aliased. The parameters to alias may be names or symbols.</p>

                <p>Does Ruby allow us to write functions that can accept variable number of parameters? Yes, see the following example - <strong>p011vararg.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p011vararg.rb
                # variable number of parameters example
                # The asterisk is actually taking all arguments you send to the method
                # and assigning them to an array named my_string as shown below
                # The do end is a Ruby block which we talk in length later
                def foo(*my_string)
                  my_string.inspect
                end
                puts foo('hello','world')
                puts foo()
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The asterisk (called the splat argument) is actually taking all arguments you send to the method and assigning them to an array named my_string. As you can see, by making use of the asterisk, we're even able to pass in zero arguments. The code above will result in the Array ['hello', 'world'] written in the first method call and an empty Array being written on the second call, as you can see in the following output:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p011vararg.rb
                ["hello", "world"]
                []
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>In Ruby, you can put the splat argument anywhere in a method's parameter list:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                def opt_args(a,*x,b)
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>What is the maximum number of parameters we can pass in Ruby? There's no limit to the number of parameters.</p>

                <p>What is the sequence in which the parameters are put on to the stack? Left to right like C or right to left like Pascal? The answer is Left to right as you can see in this example <strong>p012mtdstack.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p012mtdstack.rb
                # Sequence in which the parameters are put on to the stack is left to right
                def mtd(a=99, b=a+1)
                  [a,b]
                end
                puts mtd # displays 99, 100
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p><em>Are the parameters passed by value or reference?</em>  Observe the following example:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                def downer(string)
                  string.downcase
                end
                a = "HELLO"
                downer(a)      # -> "hello"
                puts a         # -> "HELLO"

                def downer(string)
                  string.downcase!
                end
                a = "HELLO"
                downer(a)      # -> "hello"
                puts a         # -> "hello"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Gary Wright in the Ruby forum posted in reply to some posts: "<em>It is confusing to me to even think about methods returning objects  unless you are using that as a very specific shorthand for saying that methods return *references* to objects. That is the unifying idea that helped me understand how Ruby manipulates data -- it is all references and not the objects themselves. The objects themselves are almost completely hidden from the programmer (excluding C extensions) in Ruby. Everything is a reference to an object.</em>"</p>

                <h3>Bang (!) Methods</h3>

                <p>Ruby methods that modify an object in-place and end in an exclamation mark are known as bang methods. By convention, the bang labels a method as dangerous - specifically, as the <em>dangerous</em> equivalent of a method with the same name but without the bang.<br /><br />You'll find a number of pairs of methods, one with the bang and one without. Those without the bang perform an action and return a freshly minted object, reflecting the results of the action (capitalizing a string, sorting an array, and so on). The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.<br /><br />Examples of such pairs of methods include <strong>sort/sort!</strong> for arrays, <strong>upcase/upcase!</strong> for strings, <strong>chomp/chomp!</strong> for strings, and <strong>reverse/reverse!</strong> for strings and arrays. In each case, if you call the non-bang version of the method on the object, you get a new object. If you call the bang version, you operate in-place on the same object to which you sent the message.</p>

                <p class="post-note">In Ruby you can define a method name that ends with an exclamation point or bang. The bang methods are called and executed just like any other method. However, by convention, a method with an exclamation point or bang is considered dangerous.<br /><br /><em>Normally for the built-in classes, dangerous usually (although not always) means this method, unlike its non-bang equivalent, permanently modifies its receiver</em>.<br /><br />You'll find a number of methods, one with the bang and one without. Those without the bang perform an action and return a new object. The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.<br /><br />A few non-bang methods perform changes on the original string. The names of these methods make it clear that this is happening (such as <strong>replace</strong>), even though there's no ! on the name.</p>

                <h3>Method names ending with ?</h3>

                <p>The question mark has no special meaning to the Ruby interpreter. However, by convention, any method whose name ends with ? returns a value that answers the question posed by the method invocation. The <strong>empty?</strong> method of an array, for example, returns <strong>true</strong> if the array has no elements. Mostly such methods return one of the Boolean values <strong>true</strong> or <strong>false</strong>, but this is not required, as any value other than <strong>false</strong> or <strong>nil</strong> works like <strong>true</strong> when a Boolean value is required. The <strong>Numeric</strong> method <strong>nonzero?</strong>, for example, returns <strong>nil</strong> if the number it is invoked on is zero, and just returns the number otherwise.</p>

                <h3>Summary</h3>

                <p>I have listed down all the <strong><a href="/satishtalim/ruby_summary2.html">important points</a></strong> you need to remember after you have completed the following topics: <a href="/satishtalim/scope.html">Scope</a>, <a href="/satishtalim/getting_input.html">Getting Input</a>, <a href="/satishtalim/ruby_names.html">Ruby Names</a>, <a href="/satishtalim/more_on_ruby_methods.html">More on Ruby Methods</a>, <a href="/satishtalim/writing_own_ruby_methods.html">Writing on Ruby Methods</a>.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/more_on_ruby_methods.html">&lt;More on Ruby Methods | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_ri_tool.html">Ruby ri Tool&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->
<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
